
class DockerService(object):

    # 注入 ssh 服务
    def useClient(self, client):
        self._client = client

    # 停止指定名称的容器（如果存在）
    def stop_container_if_exists(self, container_name):
        try:
            command = f"docker ps -a -f 'name={container_name}' -q"
            stdin, stdout, stderr = self._client.exec_command(command)
            container_id = stdout.read().decode().strip()
            if container_id:
                stop_command = f"docker stop {container_id}"
                stdin, stdout, stderr = self._client.exec_command(stop_command)
                print(stdout.read().decode())
                print(stderr.read().decode())
            else:
                print(f"Container {container_name} not found. Skipping stop.")
        except Exception as e:
            print(f"Error checking or stopping container {container_name}: {e}")

    # 删除指定名称的镜像
    def delete_image(self, image_name):
        try:
            command = f"docker rmi {image_name}"
            stdin, stdout, stderr = self._client.exec_command(command)
            print(stdout.read().decode())
            print(stderr.read().decode())
        except Exception as e:
            print(f"Error removing image {image_name}: {e}")

    # 使用docker-compose重新部署
    def redeploy_with_docker_compose(self, compose_file_path='docker-compose.yml'):
        try:
            # 先停止并删除现有的docker-compose服务
            self.stop_and_remove_compose_services(compose_file_path)
            
            # 然后执行docker-compose up -d
            command = f"docker-compose -f {compose_file_path} up -d"
            stdin, stdout, stderr = self._client.exec_command(command)
            print(stdout.read().decode())
            print(stderr.read().decode())
        except Exception as e:
            print(f"Error running docker-compose: {e}")

    # 停止并删除docker-compose服务
    def stop_and_remove_compose_services(self, compose_file_path='docker-compose.yml'):
        try:
            command = f"docker-compose -f {compose_file_path} down"
            stdin, stdout, stderr = self._client.exec_command(command)
            print(stdout.read().decode())
            print(stderr.read().decode())
        except Exception as e:
            print(f"Error stopping and removing docker-compose services: {e}")




# # 调用函数执行操作
# container_name = 'your_container_name'
# image_name = 'your_image_name'
# stop_container_if_exists(container_name)
# delete_image(image_name)
# redeploy_with_docker_compose()

# # 关闭SSH连接
# self._client.close()
